package org.chen.controller;

import lombok.extern.slf4j.Slf4j;
import org.chen.constants.ImageStatus;
import org.chen.model.dto.*;
import org.chen.model.sys.ImageResource;
import org.chen.model.vo.CrawlerRuleVO;
import org.chen.model.vo.CrawlerTaskVO;
import org.chen.response.Result;
import org.chen.service.CrawlerRuleService;
import org.chen.service.CrawlerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/crawler")
@Slf4j
public class CrawlerController {
    private final CrawlerService crawlerService;
    private final CrawlerRuleService crawlerRuleService;

    public CrawlerController(CrawlerService crawlerService, CrawlerRuleService crawlerRuleService) {
        this.crawlerService = crawlerService;
        this.crawlerRuleService = crawlerRuleService;
    }

    @PostMapping("/tasks")
    public Result<String> createTask(@RequestBody @Validated CrawlerTaskDTO taskDTO) {
        System.out.println(taskDTO);
        String taskId = crawlerService.createTask(taskDTO);
        return Result.success(taskId);
    }

    @DeleteMapping("/tasks/{taskId}")
    public Result<Void> stopTask(@PathVariable String taskId) {
        crawlerService.stopTask(taskId);
        return Result.success();
    }

    @DeleteMapping("/deleteTask/{taskId}")
    public Result<Void> deleteTask(@PathVariable String taskId) {
        crawlerService.deleteTask(taskId);
        return Result.success();
    }

    @GetMapping("/tasks")
    public Result<Page<CrawlerTaskVO>> getActiveTasks(ActiveTasksDto activeTasksDto) {
        return Result.success(crawlerService.getTasks(activeTasksDto));
    }

    @GetMapping("/rules")
    public Result<List<CrawlerRuleVO>> getRules() {
        return Result.success(crawlerRuleService.getRulesWithCache());
    }
}
